//
//  QTempletVC.m
//  ImageEffect
//
//  Created by lichq on 14-1-21.
//  Copyright (c) 2014年 lichq. All rights reserved.
//

#import "QTempletVC.h"
#import "ImageUtil.h"

#import "QDloadTempletVC.h"
//#import "QRegionColor.h"

#import "QTempletFile.h"


float QRegionColor10[] = {255.0, 110.0, 110.0, 100.0};
float QRegionColor11[] = {239.0, 222.0, 16.0, 255.0};
float QRegionColor12[] = {0.0, 255.0, 110.0, 255.0};
float QRegionColor13[] = {0.0, 110.0, 0.0, 1.0};
float QRegionColor14[] = {138.0, 242.0, 222.0, 200.0};
float QRegionColor15[] = {39.0, 181.0, 192.0, 0.0};
float QRegionColor16[] = {16.0, 134.0, 190.0, 200.0};
float QRegionColor17[] = {181.0, 140.0, 198.0, 255.0};

#define BOXWidth 45
#define BOXHeight 30

@implementation QTempletVC

//@synthesize templetInfoArray;
//@synthesize oldTempletInfoArray;

-(UIImage *)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    
    UIGraphicsBeginImageContext(newSize);//根据当前大小创建一个基于位图图形的环境
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];//根据新的尺寸画出传过来的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();//从当前环境当中得到重绘的图片
    UIGraphicsEndImageContext();//关闭当前环境
    
    return newImage;
}

- (QTempletInfo)getTempletInfoFromFile:(NSString *)fileTitle{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *filePath = [NSString  stringWithFormat:@"%@/%@", docDir, fileTitle];
    
    char *myFilePath = (char *)[filePath UTF8String];
    QTempletInfo tpInfoRead = getTempletInfoFromFile(myFilePath);
    return tpInfoRead;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    imageArray = [[NSMutableArray alloc]init];
}

- (void)goTemplet{
    isSegAction = YES;
    NSInteger type = seg.selectedSegmentIndex;
    [self goTemplet:type];
}




- (void)goTemplet:(NSInteger)type{
    /*
    if (type == 0) {
        templetInfo = createTempletInfo0();
        oldTempletInfo = createTempletInfo0();
    }else if(type == 1){
        templetInfo = createTempletInfo1();
        oldTempletInfo = createTempletInfo1();
    }else if(type == 2){
        templetInfo = createTempletInfo2();
        oldTempletInfo = createTempletInfo2();
    }else if(type == 3){
        templetInfo = createTempletInfo3();
        oldTempletInfo = createTempletInfo3();
    }else if(type == 4){
        templetInfo = createTempletInfo4();
        oldTempletInfo = createTempletInfo4();
    }else if(type == 5){
        templetInfo = createTempletInfo5();
        oldTempletInfo = createTempletInfo5();
    }else if(type == 6){
        templetInfo = createTempletInfo6();
        oldTempletInfo = createTempletInfo6();
    }else if(type == 7){
        templetInfo = createTempletInfo7();
        oldTempletInfo = createTempletInfo7();
    }
    */
    
    
//    [[self.templetInfoArray objectAtIndex:type] getValue:&tpInfo];
//    [[self.oldTempletInfoArray objectAtIndex:type] getValue:&oldTpInfo];
    
    
    NSString *fileTitle = [tpTitleArray objectAtIndex:type];

    tpInfo = [self getTempletInfoFromFile:fileTitle];
    //int length =  strlen(tpRead.templetPixel);
    int templetW = tpInfo.templetW;
    int templetH = tpInfo.templetH;
    int length = templetW * templetH * 4;
    oldPixelOld = (unsigned char *)calloc(length, sizeof(unsigned char));
    for (int i = 0; i<length; i++) {
        oldPixelOld[i] = tpInfo.templetPixel[i];
    }
    
    
    if (isSegAction == YES) {
        for (int i = 0; i < imageArray.count && i < tpInfo.regionCount; i++) {
            UIImage *image = [imageArray objectAtIndex:i];
            tpInfo = [ImageUtil QFillImage:image ToTempletInfo:tpInfo InRegion:i];
            
            isSegAction = NO;
        }
    }else{
        
    }
    
    
    imageView.image = [QImage createNewImageByImagePixel:tpInfo.templetPixel width:tpInfo.templetW height:tpInfo.templetH];
}



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSSet *allTouches = [event allTouches];
    UITouch *touch = [allTouches anyObject];
//    CGPoint point = [touch locationInView:[touch view]];
    CGPoint point = [touch locationInView:imageView];
    int x = point.x;
    int y = point.y;
    
    x = x * tpInfo.templetW / imageView.frame.size.width;   //由中的点的位置计算得到该点应在模板中的对应位置
    y = y * tpInfo.templetH / imageView.frame.size.height;
    
    if (tpInfo.templetPixel == nil) {
        return;
    }

    unsigned char *oldTempletPixel = oldPixelOld;
    int w = tpInfo.templetW;
    if (x < 0 || y < 0 || x > w) {
        int byte = (y*w+x) * 4;
        NSLog(@"(%3d,%3d) is region out, %d,%d,%d,%d", x, y, oldTempletPixel[byte], oldTempletPixel[byte+1], oldTempletPixel[byte+2], oldTempletPixel[byte+3]);
        return;
        
    }
    
    
    if (isCuPixelColorEqualRegionColor(oldTempletPixel, x, y, w, QRegionColor10)) {
        selRegion = 0;
    }else if (isCuPixelColorEqualRegionColor(oldTempletPixel, x, y, w, QRegionColor11)) {
        selRegion = 1;
    }else if (isCuPixelColorEqualRegionColor(oldTempletPixel, x, y, w, QRegionColor12)) {
        selRegion = 2;
    }else if (isCuPixelColorEqualRegionColor(oldTempletPixel, x, y, w, QRegionColor13)) {
        selRegion = 3;
    }else if (isCuPixelColorEqualRegionColor(oldTempletPixel, x, y, w, QRegionColor14)) {
        selRegion = 4;
    }else if (isCuPixelColorEqualRegionColor(oldTempletPixel, x, y, w, QRegionColor15)) {
        selRegion = 5;
    }else if (isCuPixelColorEqualRegionColor(oldTempletPixel, x, y, w, QRegionColor16)) {
        selRegion = 6;
    }else if (isCuPixelColorEqualRegionColor(oldTempletPixel, x, y, w, QRegionColor17)) {
        selRegion = 7;
    }else{
        selRegion = -1;
    }
    
    if (selRegion == -1) {
        int byte = (y*w+x) * 4;
        NSLog(@"(%3d,%3d) is region out, %d,%d,%d,%d", x, y, oldTempletPixel[byte], oldTempletPixel[byte+1], oldTempletPixel[byte+2], oldTempletPixel[byte+3]);
    }else{
        NSLog(@"(%3d,%3d) is region %d", x, y, selRegion);
    }
    
    
    
    if (selRegion != -1) {
        [self goChooseImage];
    }

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    tpTitleArray = [[NSUserDefaults standardUserDefaults] arrayForKey:@"templetTitle"];
    if (tpTitleArray == nil || tpTitleArray.count == 0) {
        return;
    }
    
    [openImageBtn setTitle:@"添加多张图片" forState:UIControlStateNormal];
    
    NSInteger templetCount = tpTitleArray.count;
    
    scrollerView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 340, 320, 100)];
    scrollerView.backgroundColor = [UIColor clearColor];
    scrollerView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
    scrollerView.showsHorizontalScrollIndicator = YES;
    scrollerView.showsVerticalScrollIndicator = NO;
    scrollerView.bounces = NO;//取消反弹效果
    scrollerView.pagingEnabled = NO;//划一屏
    scrollerView.contentSize = CGSizeMake(BOXWidth * templetCount, 30);
    [self.view addSubview:scrollerView];
    
    
    seg = [[UISegmentedControl alloc]initWithItems:tpTitleArray];
    seg.segmentedControlStyle = UISegmentedControlStyleBar;//样式
    seg.momentary = NO;//点击后恢复原样
    seg.frame = CGRectMake(0, 50, BOXWidth * templetCount, 30);
    seg.tintColor = [UIColor redColor];
    [seg addTarget:self action:@selector(goTemplet) forControlEvents:UIControlEventValueChanged];
    [scrollerView addSubview:seg];

    
    for(int i=0;i<[tpTitleArray count];i++)
    {
        UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10 + BOXWidth*i, 10, 25, BOXHeight)];
        
        NSString *imageName = [NSString stringWithFormat:@"%d.png",i];
        
        bgImageView.image = [UIImage imageNamed:imageName];
        [scrollerView addSubview:bgImageView];
    }
    
    NSInteger selType = [[NSUserDefaults standardUserDefaults] integerForKey:@"templet_select"];
    if (selType == -1) {
        seg.selectedSegmentIndex = 0;
        [self goTemplet:seg.selectedSegmentIndex];
    }else{
        seg.selectedSegmentIndex = selType;
    }
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
//    self.navigationController.toolbarHidden = YES;
    
    if (seg != nil && seg.selectedSegmentIndex != -1) {
        [[NSUserDefaults standardUserDefaults] setInteger:seg.selectedSegmentIndex forKey:@"templet_select"];
    }
}

-(void)loadView
{
    
    self.view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.view.backgroundColor = [UIColor blackColor];
    
    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 10, 240, 320)];//必须跟模板大小一样，否则影响触摸区域判断
    imageView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:imageView];
    
    openImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [openImageBtn setFrame:CGRectMake(100, 160, 120, 30)];
    [openImageBtn setBackgroundColor:[UIColor orangeColor]];
    if (tpTitleArray == nil || tpTitleArray.count == 0) {
        [openImageBtn setTitle:@"下载添加模板" forState:UIControlStateNormal];
    }else{
        [openImageBtn setTitle:@"添加多张图片" forState:UIControlStateNormal];
    }
    [openImageBtn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:openImageBtn];
    
    
    self.navigationItem.title = @"图片处理";
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(goBack)];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(goSave)];
    UIBarButtonItem *right2 = [[UIBarButtonItem alloc]initWithTitle:@"下载" style:UIBarButtonItemStyleBordered target:self action:@selector(goDload)];
    self.navigationItem.leftBarButtonItem = left;
//    self.navigationItem.rightBarButtonItem = right;
    self.navigationItem.rightBarButtonItems = [[NSMutableArray alloc]initWithObjects:right, right2, nil];
    
    /*
    self.navigationController.toolbarHidden = NO;
    self.navigationController.toolbar.barStyle = UIBarStyleBlack;
    
    UIBarButtonItem *origin = [[UIBarButtonItem alloc]initWithTitle:@"模1" style:UIBarButtonItemStyleDone target:self action:@selector(goTemplet1)];
    origin.tintColor = [UIColor blackColor];
    UIBarButtonItem *blackWhite = [[UIBarButtonItem alloc]initWithTitle:@"模2" style:UIBarButtonItemStyleDone target:self action:@selector(goTemplet2)];
    blackWhite.tintColor = [UIColor blackColor];
    NSArray *arr = [NSArray arrayWithObjects:origin,blackWhite, nil];
    [self setToolbarItems:arr animated:YES];
    */
    

    
}


- (void)goBack{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)btnAction{
    if (tpTitleArray == nil || tpTitleArray.count == 0) {
        [self goDload];
    }else{
        [self goChooseImage];
    }
}

- (void)goDload{
    QDloadTempletVC *nextCon = [[QDloadTempletVC alloc]init];
    [self.navigationController pushViewController:nextCon animated:YES];
}


-(void)goChooseImage{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"打开图片" delegate:self cancelButtonTitle:@"关闭" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"照相机", nil];
    sheet.delegate = self;
    sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;//样式
//    [sheet showInView:self.view];//显示样式
    [sheet showFromToolbar:self.navigationController.toolbar];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 0){
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;//过渡类型,有四种
        imagePicker.allowsEditing = NO;//对图片进行编辑
        
        [self presentViewController:imagePicker animated:YES completion:NULL];
    }else if(buttonIndex == 1){
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            
            [self presentViewController:imagePicker animated:YES completion:NULL];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该设备没有照相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];//获取图片
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//将拍到的图片保存到相册
    }
    
    if (tpInfo.regionInfo[selRegion].existImage == false) {
        [imageArray addObject:image];
        tpInfo.regionInfo[selRegion].existImage = true;
    }else{
        int imageIndex = -1;
        for (int i = 0; i< tpInfo.regionCount; i++) {
            if (tpInfo.regionInfo[i].existImage) {
                imageIndex ++;
            }
            if (i == selRegion) {
                break;
            }
        }
        [imageArray replaceObjectAtIndex:imageIndex withObject:image];
    }
    //NSLog(@"imageArray = %@", imageArray);
    
    
    tpInfo = [ImageUtil QFillImage:image ToTempletInfo:tpInfo InRegion:selRegion];
    imageView.image = [QImage createNewImageByImagePixel:tpInfo.templetPixel width:tpInfo.templetW height:tpInfo.templetH];
    
    if ([openImageBtn isDescendantOfView:self.view]) {
        [openImageBtn removeFromSuperview];
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];//关闭模态视图控制器
}



-(void)goSave{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存", nil];
    alert.delegate = self;
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1){
        UIImage *image = imageView.image;// 要保存的图片
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);// 保存图片到相册中
    }
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error != NULL){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"保存失败,请重新保存" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
        //        alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
        [alert show];
    }
    else// 没有error
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"保存成功" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
        [alert show];
    }
}

@end
